package com.secondweek.获取当前天气;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import net.sf.json.JSONObject;
/**
 * @description: 获取当前天气
 * @author: 十月
 * @create: 2020-11-29 12:57
 **/
public class Third {
    public static Map<String,Object> getWeather(String cityid)
    {
        Map<String, Object>  map = new HashMap<String, Object>();
        // 连接中央气象台的API
        try {
            URL url = new URL("http://www.weather.com.cn/data/cityinfo/" + cityid+".html");
            URLConnection connectionData = url.openConnection();
            //超时报错
            connectionData.setConnectTimeout(1000);
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    connectionData.getInputStream(), "UTF-8"));
            StringBuilder sb = new StringBuilder();
            String line ;
            while ((line = br.readLine()) != null)
                sb.append(line);
            String data = sb.toString();
            //System.out.println(data);
            JSONObject jsonData = JSONObject.fromObject(data);
            JSONObject info = jsonData.getJSONObject("weatherinfo");
            // 城市
            map.put("city", info.getString("city").toString());
            // 最高温度
            map.put("temp1", info.getString("temp1").toString());
            // 最低温度
            map.put("temp2", info.getString("temp2").toString());
            //天气
            map.put("weather", info.getString("weather").toString());
            // 发布时间
            map.put("ptime", info.getString("ptime").toString());
        } catch (MalformedURLException e) {
            System.out.println("该地址不存在！");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("连接错误！");
            e.printStackTrace();
        }
        return map;
    }

    public static void main(String[] args) {
        try {
            //测试获取实时天气2(包含天气，温度范围)
            Map<String, Object> map = getWeather("101110101"); //这块填的是城市编码
            System.out.println("当前城市："+map.get("city"));
            System.out.println("当前天气："+map.get("weather"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
